// @ts-nocheck
import React, { useState, useEffect, useCallback, useRef } from "react";
import { Button, Input, Toast } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import "./index.less";
// 防抖函数
function debounce(func, delay) {
  let timer;
  return function () {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, arguments);
    }, delay);
  };
}
// 是否为空对象
function isEmptyObject(obj) {
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      return false;
    }
  }
  return true;
}
function MapComponent({ isSearch = true }) {
  const navigate = useNavigate();
  const latestInfo = useRef({
    map: "",
    localsearch: "",
    geocode: "",
  });
  const formItem = useRef();
  const addressItem = useRef();
  const [searchResultsList, setSearchResultsList] = useState([]); //关键词列表
  const [searchValue, setSearchValue] = useState([]); //搜索框的值
  const [searchResults, setSearchResults] = useState([]); //监听搜索的输入框输入集合
  const [itemImforMation, setItemImforMation] = useState({}); //点位信息
  const url = window.location.search.split("=")[1];

  useEffect(() => {
    onLoad();
  }, []);

  async function onLoad() {
    //初始化地图对象
    const map = await new T.Map("container");
    //设置显示地图的中心点和级别
    map.centerAndZoom(new T.LngLat(106.63, 30.46), 15);
    //允许鼠标滚轮缩放地图
    let config = {
      pageCapacity: 10, //每页显示的数量
      onSearchComplete: localSearchResult, //接收数据的回调函数
    };
    //创建搜索对象
    latestInfo.current.localsearch = new T.LocalSearch(map, config);
    latestInfo.current.map = map;
    latestInfo.current.geocode = new T.Geocoder();

    // 地图点击事件
    map.addEventListener("click", debounce(MapClick, 1500));

    Toast.show({
      icon: "loading",
      content: "定位中…",
      duration: 0,
    });
    setTimeout(function () {
      Toast.clear();
    }, 3000);

    // 获取实时定位
    var lo = new T.Geolocation();
    let fn = function (e) {
      if (e.lnglat) {
        Toast.show({
          content: "定位成功",
          duration: 1000,
        });
        const getAddress = (endValue) => {
          const imforData = {
            city: endValue?.addressComponent?.city,
            district: endValue?.addressComponent?.county,
            street: endValue?.addressComponent?.road,
            lng: endValue?.location?.lon,
            lat: endValue?.location?.lat,
            longitude: endValue?.location?.lon,
            latitude: endValue?.location?.lat,
            address: endValue?.formatted_address,
            addressDetailedUser: endValue?.formatted_address,
          };
          setSearchValue(endValue?.formatted_address);
          setItemImforMation(imforData);
          localStorage.setItem("address", JSON.stringify(imforData));
        };
        latestInfo.current.geocode.getLocation(e.lnglat, getAddress);
        if (this.getStatus() == 0) {
          latestInfo.current.map?.centerAndZoom(e.lnglat, 15);
          var marker = new T.Marker(e.lnglat);
          latestInfo.current.map.addOverLay(marker);
        }
        if (this.getStatus() == 1) {
          latestInfo.current.map?.centerAndZoom(e.lnglat, e.level);
          var marker = new T.Marker(e.lnglat);
          latestInfo.current.map.addOverLay(marker);
        }
      } else {
        Toast.show("无法获取当前定位！");
      }
    };
    lo.getCurrentPosition(fn);
  }

  if (
    !isEmptyObject(
      JSON.parse(localStorage.getItem("form") || JSON.stringify(""))
    )
  ) {
    formItem.current = JSON.parse(
      localStorage.getItem("form") || JSON.stringify("")
    );
    addressItem.current = JSON.parse(
      localStorage.getItem("address") || JSON.stringify("")
    );
  }
  function localSearchResult(result) {
    //清空地图及搜索列表
    clearAll();
    //解析建议词信息
    setSearchResultsList(result?.pois);
  }

  // 点击推荐建议词
  function clickValue(value, itemImfor) {
    const imforData = {
      longitude: itemImfor?.lonlat?.split(",")[0],
      latitude: itemImfor?.lonlat?.split(",")[1],
      lng: itemImfor?.lonlat?.split(",")[0],
      lat: itemImfor?.lonlat?.split(",")[1],
      address: itemImfor?.address + itemImfor?.name,
      addressDetailedUser: itemImfor?.address + itemImfor?.name,
    };
    setSearchValue(itemImfor?.address + itemImfor?.name);
    setItemImforMation(imforData);
  }

  //清空地图及搜索列表
  function clearAll() {
    setSearchResultsList([]);
  }
  // 点击搜索
  function searchAddress() {
    let lng = itemImforMation?.longitude;
    let lat = itemImforMation?.latitude;
    let marker = new T.Marker(itemImforMation);
    if (latestInfo.current.map.getOverlays().length > 0) {
      latestInfo.current.map.clearOverLays();
    }

    latestInfo.current.map.addOverLay(marker);
    latestInfo.current.map.panTo(new T.LngLat(lng, lat));
  }

  /* 搜索功能 */
  const handleSearchChange = useCallback((e) => {
    setSearchValue(e); // 监听搜索框的输入
  }, []);

  const debouncedSearch = useCallback(
    () => {
      // 使用 debounce 函数实现节流
      setSearchResults([...searchResults, searchValue]);
    },
    [searchValue],
    1000
  );

  useEffect(() => {
    const timer = setTimeout(() => {
      debouncedSearch(); // 在组件挂载和卸载时清除 debouncedSearch 的定时器
    }, 1000);
    return () => {
      clearTimeout(timer);
    };
  }, [debouncedSearch]);

  useEffect(() => {
    latestInfo.current.localsearch?.search(
      searchResults[searchResults?.length - 1]
    );
  }, [searchResults]);

  // 点击定位
  function clickSearchResult(result) {
    if (result.getAddress()) {
      const imforData = {
        city: result?.addressComponent?.city,
        district: result?.addressComponent?.county,
        street: result?.addressComponent?.road,
        longitude: result?.location?.lon,
        latitude: result?.location?.lat,
        lng: result?.location?.lon,
        lat: result?.location?.lat,
        address: result?.formatted_address,
        addressDetailedUser: result?.formatted_address,
      };
      setSearchValue(result?.formatted_address);
      setItemImforMation(imforData);
      let marker = new T.Marker(result?.location);
      if (latestInfo.current.map.getOverlays().length > 0) {
        latestInfo.current.map.clearOverLays();
      }
      latestInfo.current.map.addOverLay(marker);
    }
  }

  function MapClick(e) {
    latestInfo.current.geocode.getLocation(e.lnglat, clickSearchResult);
  }

  // 返回路由
  function getUrl() {
    let newUrl = "";
    if (url == "eventReport") {
      newUrl = "/eventReport";
    } else if (url == "emergencyReporting") {
      newUrl = "/emergencyReporting";
    } else if (url?.indexOf("communityServiceReport") !== -1) {
      newUrl = `/${window.location.search.split("=")[1]}`;
    } else {
      newUrl = `/eventReport`;
    }
    return newUrl;
  }
  function handleOk() {
    let formItem1 = formItem.current ? formItem.current : {};
    let addressItem1 = addressItem.current ? addressItem.current : {};
    formItem1.address = itemImforMation?.address;
    formItem1.addressDetailedUser = itemImforMation?.addressDetailedUser;
    const newFormItem = { ...formItem1 };
    if (itemImforMation.longitude && itemImforMation.latitude) {
      addressItem1.longitude = itemImforMation?.longitude;
      addressItem1.latitude = itemImforMation?.latitude;
    }
    localStorage.setItem("form", JSON.stringify(newFormItem));
    localStorage.setItem(
      "address",
      JSON.stringify({ ...itemImforMation, ...addressItem1 })
    );
    // navigate(getUrl())
    navigate(-1);
  }

  // 返回按钮
  function handleCancel() {
    let formItem1 = formItem.current ? formItem.current : {};
    let addressItem1 = addressItem.current ? addressItem.current : {};
    localStorage.setItem("form", JSON.stringify(formItem1));
    localStorage.setItem("address", JSON.stringify(addressItem1));
    navigate(-1);
  }
  return (
    <>
      <div id="container" className="map" style={{ height: "100vh" }}></div>
      <div className="back">
        <Button
          style={{ fontSize: "2rem" }}
          color="primary"
          fill="solid"
          onClick={() => handleCancel()}
        >
          返回
        </Button>
      </div>
      <div className="submit">
        <Button
          style={{ fontSize: "2rem" }}
          color="primary"
          fill="solid"
          onClick={() => handleOk()}
        >
          确定
        </Button>
      </div>
      {isSearch && (
        <div
          style={{
            position: "absolute",
            bottom: "11rem",
            left: "0vw",
            right: "0vw",
            display: "flex",
            justifyContent: "center",
            zIndex: "1000",
            height: "4rem",
          }}
        >
          <Input
            id="tipinput"
            style={{
              width: "80vw",
              height: "100%",
              backgroundColor: "white",
              paddingLeft: 10,
              fontSize: "2rem",
            }}
            className="input"
            placeholder="请输入想要搜索的地址"
            value={searchValue}
            clearable
            onChange={handleSearchChange}
            onPressEnter={debouncedSearch}
          />
          <Button
            color="primary"
            fill="solid"
            onClick={() => {
              searchAddress();
            }}
            style={{ height: "100%", fontSize: "2rem" }}
          >
            搜索
          </Button>
          {searchResultsList.length > 0 ? (
            <div id="suggestsDiv" className="suggests">
              {searchResultsList?.map((item, index) => {
                return (
                  <div
                    key={index}
                    onClick={() => {
                      clickValue(item?.address + item?.name, item);
                    }}
                  >
                    <div className="resultName">{item?.name}</div>
                    <div className="resultAddress">{item?.address}</div>
                  </div>
                );
              })}
            </div>
          ) : null}
        </div>
      )}
    </>
  );
}

export default MapComponent;
